﻿using System;
using System.ServiceModel;
using System.Web;
using DXWebApplication.NewsServiceReference;

namespace DXWebApplication.Repositories.Core.News
{
    public abstract class NewsRepositoryBase
    {
        /// <summary>
        /// Gets the news service client.
        /// </summary>
        /// <value>
        /// The news service client.
        /// </value>
        protected ActionNewsServiceClient NewsServiceClient
        {
            get
            {
                // Check if not initialized yet
                if (HttpContext.Current.Session["NewsServiceClient"] == null)
                    HttpContext.Current.Session["NewsServiceClient"] = new  ActionNewsServiceClient();

                // If current client is 'faulted' (due to some error), create a new instance.
                var client = HttpContext.Current.Session["NewsServiceClient"] as ActionNewsServiceClient;
                if (client != null && client.State == CommunicationState.Faulted)
                {
                    try { client.Abort(); }
                    catch { /* no action */ }

                    client = new ActionNewsServiceClient();
                    HttpContext.Current.Session["NewsServiceClient"] = client;
                }
                return client;
            }
        }

        /// <summary>
        /// Correlates requestid with returned response correlationId. 
        /// These must always match. If not, request and responses are not related.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected void Correlate(RequestBase request, ResponseBase response)
        {
            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("RequestId and CorrelationId do not match.");
        }
    }
}